#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include "queue.h"


sem_t semr,semw;
struct queue *que;
int data = 0;
pthread_mutex_t  mutex;



void *fun1(void *arg)
{
	int dat = 0;

	while(1)
	{
		printf("please input data:\n");
		//scanf("%d",&dat);
		dat = dat + 1;


		sem_wait(&semw);
		pthread_mutex_lock(&mutex);
		push(dat,que);
		sem_post(&semr);

		pthread_mutex_unlock(&mutex);
	}
}

void *fun2(void *arg)
{
	int dat = 0;
	while(1)
	{

		sem_wait(&semr);
		pthread_mutex_lock(&mutex);
		dat = front(que);
		pop(que);
		sem_post(&semw);

		pthread_mutex_unlock(&mutex);

	//	sleep(1);

		dat = dat + 2;
		printf("%d\n",dat);
		printf("queue'size is %d\n",size(que));
		
	}


}

int main()
{

	pthread_t tid1 = 0,tid2 = 0;
	int ret = 0;


	sem_init(&semw,0,1000);
	sem_init(&semr,0,0);
	que = create_queue();
	pthread_mutex_init(&mutex,NULL);

	ret = pthread_create(&tid1,NULL,fun1,NULL);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}

	ret = pthread_create(&tid2,NULL,fun2,NULL);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}
	
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);

	sem_destroy(&semr);
	sem_destroy(&semw);



	return 0;

}





